
let _Vue = null
class VueRouter {
    static install(Vue) {
        if (VueRouter.install.installed) return
        VueRouter.install.installed = true
        _vue = Vue

        _vue.mixin({
            brforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                }
            }
        })
    }
    constructor(options) {
        this.options = options
        this.routerMap = {}
        this.data = _vue.observable({
            current: '/'
        })
        this.init()
    }
    init() {
        this.createRouteMap()
        this.initComponent()
        this.initEvent()
    }
    initComponent(Vue) {
        const self = this
        Vue.component('router-view', {
            render(h) {
                const cm = self.routerMap[self.data.current]
                return h(cm)
            }
        })
        Vue.component('router-link', {
            props: {
                to: String
            },
            render(h) {
                return h('a', {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickHander
                    }
                }, [this.$slot.default])
            },
            methods: {
                clickHander(e) {
                    history.pushState({}, '', this.to)
                    this.$router.data.current = this.to
                    e.preventDefault()
                }
            }
        })
    }
    createRouteMap(){
        //遍历所有的路由规则 吧路由规则解析成键值对的形式存储到routeMap中
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        });
    }
    initEvent(){
        //
        window.addEventListener("hashchange",()=>{
            this.data.current = window.location.hash.replace('#', '')
        }, false)
        // window.addEventListener("popstate",()=>{
        //     this.data.current = window.location.hash.replace('#', '')
        // }, false)
    }
}